# -*- coding: utf-8 -*-
"""
@Time ： 2024/12/9 14:59
@Auth ： 周瑞东 Ryan.Zhou
@File ：hal_serial.py
"""
import time
import threading
from utils.global_state import GlobalState
import RPi.GPIO as GPIO
from hal.lib_dht11 import dht11


class HALDHT11:
    _instance = None

    def __new__(cls):
        """确保只有一个串口实例"""
        if cls._instance is None:
            cls._instance = super(HALDHT11, cls).__new__(cls)
            cls._instance.serial_port_handler = None
            cls._instance.__global_state = GlobalState()
        return cls._instance

    def __init__(self):
        if not hasattr(self, '_initialized'):  # 确保只初始化一次
            self.dht11_pin = 21
            
            GPIO.setwarnings(False)
            GPIO.setmode(GPIO.BCM)
            self.instance = dht11.DHT11(pin=self.dht11_pin)

            self.debug = True

            self._initialized = True
    
    def read_dht11(self):
            result = self.instance.read()
            if result.is_valid():
                print("Temp: %d C" % result.temperature +' '+"Humid: %d %%" % result.humidity)
                return [result.temperature, result.humidity]
            else:
                 return None
            # time.sleep(1)